(function () {
  'use strict';

  angular
    .module('vboxApp')
    .factory('authService', authService);

  /** @ngInject */
  function authService($sessionStorage, $rootScope, $http,$base64, $q, jwtHelper) {

    var endpoint = "http://passport.data-x.cn";
    var clientId = "avcdata";
    var clientSecret = "new.1234";

    if ($sessionStorage.userToken && !jwtHelper.isTokenExpired($sessionStorage.userToken)) {
      $rootScope.currentUser = $sessionStorage.user;
      $rootScope.isLogged = true;
    }
    else {
      $rootScope.currentUser = {};
      $rootScope.isLogged = false;
    }


    return {
      login: function (name, password, callback) {
        var cb = callback || angular.noop;
        var deferred = $q.defer();
        $http(
          {
            url: endpoint + '/oauth/token?client_id=' + clientId + '&grant_type=password&username=' + name + '&password=' + password + '&client_secret=' + clientSecret,
            headers: {
              'Authorization': 'Basic '+$base64.encode(clientId+":"+clientSecret)
            },
            method: 'POST'
          }
        ).success(function (token) {
          $sessionStorage.userToken = token.access_token;
          var user = jwtHelper.decodeToken(token.access_token);
          $sessionStorage.user = user;
          $rootScope.currentUser = user;
          console.info($rootScope.currentUser);
          $rootScope.isLogged = true;
          deferred.resolve(user);
          return cb();
        })
          .error(function error(err) {
            deferred.reject(err);
            return cb();
          });
        return deferred.promise;
      },
      logout: function () {
        delete $sessionStorage.userToken;
        delete $rootScope.currentUser;
        delete $sessionStorage.user;
        $rootScope.isLogged = false;
      },
      resetPassword: function (resetInfo, callback) {
        //console.info(resetInfo);
        $http.post(endpoint + '/reset', resetInfo).success(function (data) {
          callback(data);
        });
      }
    };
  }

})();
